package com.newidea.jiangong;

import org.eclipse.paho.client.mqttv3.*;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication(scanBasePackages = "com.newidea.jiangong")
@MapperScan("com.newidea.jiangong.mapper")
@EnableScheduling
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);

        //startMqtt();
    }

    public static void startMqtt() {
        String broker = "tcp://mqtt.usr.cn:1883";
        String clientId = "heat";
        String topic = "PubTopic1";

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            System.out.println("Connecting to broker: " + broker);
            // 设置连接的用户名
            options.setUserName("usr.cn");
            // 设置连接的密码
            options.setPassword("usr.cn".toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置断开后重新连接
            options.setAutomaticReconnect(true);
            sampleClient.connect(options);
            System.out.println("Connected");
            sampleClient.subscribe(topic);

            System.out.println("Subscribed to topic: " + topic);
            sampleClient.setCallback(new MqttCallback() {
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Message arrived: " + new String(message.getPayload()));
                    System.out.println("Message arrived: " + message);
                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("Delivery complete");
                }

                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost");
                }
            });

        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}